<template>
  <tui-bottom-popup :show="show" mark-close @close="close">
    <view class="padding-bottom-button">
      <view class="padding-top-30 padding-lr-30">
        <view class="flex-row flex-center relative">
          <text class="text-32 color-t1 text-bold">购买信息</text>
          <viwe class="close flex-row flex-center padding-10">
			<text class="tbb-guanbi1 text-36 color-t1" @click="close"></text>
          </viwe>
        </view>

        <view class="text-center margin-top-10">
          <text class="text-48 color-primary text-bold">¥{{ info.realPrice }}</text>
        </view>

        <view class="margin-top-30">
          <text class="text-28 color-t3">会员：</text>
          <text class="text-28 color-t1">{{ info.productName }}</text>
        </view>

        <view class="margin-top-10">
          <text class="text-28 color-t3">会员期限：</text>
          <text class="text-28 color-t1">{{ freeMonth(info.vipMonth) }}</text>
        </view>

        <view class="margin-top-10">
          <text class="text-28 color-t3">购买后有效期至：</text>
          <text class="text-28 color-t1">{{ showValidityPeriod }}</text>
        </view>

        <view class="margin-top-10 margin-bottom-30">
          <text class="text-28 color-error">说明：会员服务开通后不支持退款</text>
        </view>

        <l-title title="支付方式" />

        <pay-way @change="changePayWay" />
      </view>
      <safe-area-bottom />
      <l-bottom-button text="立即付款" background="#ffffff" :box-shadow="false" @click="confirm" />
    </view>
  </tui-bottom-popup>
</template>

<script>
import PayWay from '../pay-way/pay-way'
import { mapMutations } from 'vuex'
import { loading } from '@/common/util'
import { getWxspSessionKey, createVIPPayOrder } from '../../api'
import { getVipRecord } from '@/common/api/user'
export default {
  name: 'BuyVipInfo',
  components: {
    PayWay
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      payWayInfo: {},
      payInfo: {},
      loading: null,
      /* #ifdef MP-WEIXIN*/
      providerId: 'weixinCompany',
      /* #endif*/
      /* #ifdef APP-PLUS*/
      providerId: 'appCompany'
      /* #endif*/
    }
  },
  computed: {
    freeMonth() {
      return (month) => {
        if (!month) {
          return '0月'
        }
        if (month < 12) {
          return month + '月'
        } else {
          const y = parseInt(month / 12)
          const m = month % 12
          return y + '年' + (m ? m + '月' : '')
        }
      }
    },
    showValidityPeriod() {
      return this.info.vipExpirationDate ? this.info.vipExpirationDate.substring(0, this.info.vipExpirationDate.indexOf(' ')) : ''
    }
  },
  methods: {
    close() {
      this.$emit('close')
      this.$emit('update:show', false)
    },
    changePayWay(e) {
      this.payWayInfo = e
    },
    async confirm() {
      this.close()
      this.loading = loading('请稍后')
      /* #ifdef APP-PLUS*/
      await this.createOrder('', this.payWayInfo.payType)
      /* #endif*/
      // #ifdef MP-WEIXIN
      this.getPayInfo('wxpay').then(async id => {
        await this.createOrder(id, 4)
      })
      // #endif
    },
    // 获取支付信息
    getPayInfo(provider) {
      return new Promise((resolve, reject) => {
        uni.login({
          provider,
          success: async(loginRes) => {
            const openId = await this.getOpenIdByCode(loginRes.code)
            resolve(openId)
          }
        })
      })
    },
    // 获取支付openid
    async getOpenIdByCode(jsCode) {
      const [err, res] = await getWxspSessionKey({
        jsCode,
        providerId: this.providerId
      })
      if (!this.$http.errorCheck(err, res)) return false
      return res.data.data
    },
    // 创建订单
    async createOrder(openId, payType) {
      const [err, res] = await createVIPPayOrder({
        openId,
        payType,
        providerId: this.providerId,
        vipServiceInfoId: this.info.productId
      })
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      this.orderInfo = data
      if (!this.payInfo.prepay_id) this.payInfo = JSON.parse(data.payment.orderInfo)
      this.pay(this.payInfo, this.providerId).then(res => {
        this.showIndex = false
        this.getVipRecord()
      }).catch(err => {
        this.loading.hide()
        this.toast('支付失败')
      })
    },
    // 获取会员信息
    async getVipRecord() {
      const [err, res] = await getVipRecord()
      this.loading.hide()
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      this.setVipInfo(data[0])
      this.$emit('success')
    },
    // 支付
    pay(payInfo, providerId) {
      return new Promise((resolve, reject) => {
        let send = {}
        /* #ifdef MP-WEIXIN*/
        send = {
          provider: payInfo.provider,
          timeStamp: payInfo.timeStamp,
          nonceStr: payInfo.nonceStr,
          package: payInfo.package,
          signType: payInfo.signType,
          paySign: payInfo.paySign
        }
        /* #endif*/
        /* #ifdef APP-PLUS*/
        if (providerId === 'appleiap') {
          send = {
            provider: providerId,
            orderInfo: {
              productid: payInfo
            }
          }
        } else {
          send = {
            provider: payInfo.provider || providerId,
            orderInfo: payInfo
          }
        }
        /* #endif*/
        // if(providerId==='alipay') send.orderInfo=send.orderInfo.body
        uni.requestPayment(Object.assign(send, {
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        }))
      })
    },
    ...mapMutations({
      setVipInfo: 'user/setVipInfo'
    })
  }
}
</script>

<style scoped lang="scss">
.close{
  @include position(absolute, -20rpx, -16rpx);
}
</style>
